package util.boyaa 
{
	import com.boyaa.shells.control.ButtonManager;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	/**
	 * pageup & pagedown 控件
	 * 通过dispatcher()侦听翻页事件（PAGE_UP， PAGE_DOWN）
	 * @author Henrylee
	 */
	public final class PageController 
	{
		/**
		 * dispatcher.dispatchEvent(new Event(PAGE_UP));
		 */
		public static const PAGE_UP: String   = "page_up";
		/**
		 * dispatcher.dispatchEvent(new Event(PAGE_DOWN));
		 */
		public static const PAGE_DOWN: String = "page_down";
		/**
		 * 聚合一个EventDispatcher，避免深度继承
		 */
		private var m_dispatcher: EventDispatcher;
		
		private var m_view: MovieClip;
		private var m_totalPage: int;
		private var m_currentPage: int = 1;
		
		/**
		 * 初始化控件
		 * @param	mc
		 * @param	nPage 总共有多少页
		 */
		public function PageController(mc: MovieClip, nPage:int) 
		{
			m_totalPage = nPage;
			m_totalPage = m_totalPage > 0 ? m_totalPage : 1;
			
			m_view = mc;
			m_dispatcher = new EventDispatcher();
			
			MCUtil.StopDisplayList(mc);
			updateController();
		}
		
		public function addEvent():void
		{
			ButtonManager.instance.addButton(ButtonManager.ACTION_CENTER, m_view["pre"], onPageDown);
			ButtonManager.instance.addButton(ButtonManager.ACTION_CENTER, m_view["next"], onPageUp);
		}
		
		public function removeEvent():void
		{
			ButtonManager.instance.removeButton(ButtonManager.ACTION_CENTER, m_view["pre"]);
			ButtonManager.instance.removeButton(ButtonManager.ACTION_CENTER, m_view["next"]);
		}
		
		public function resetPageCount(current: int, total: int):void
		{
			m_totalPage = total;
			m_totalPage = m_totalPage > 0 ? m_totalPage : 1;
			
			m_currentPage = current;
			m_currentPage = m_currentPage > 0 ? m_currentPage : 1;
			
			updateController();
		}
		
		private function updateController():void
		{
			TextField(m_view["txt"]).text = m_currentPage + "/" + m_totalPage;
		}
		
		private function onPageUp(e:MouseEvent):void 
		{
			e.stopPropagation();
			if (m_currentPage < m_totalPage)
			{
				m_currentPage += 1;
				dispatcher.dispatchEvent(new Event(PAGE_UP));
				updateController();
			}
		}
		
		private function onPageDown(e:MouseEvent):void 
		{
			e.stopPropagation();
			if (m_currentPage > 1)
			{
				m_currentPage -= 1;
				dispatcher.dispatchEvent(new Event(PAGE_DOWN));
				updateController();
			}
		}
		
		public function get dispatcher():EventDispatcher 
		{
			return m_dispatcher;
		}
		
	}

}